package util.serviceUtil;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.support.annotation.Nullable;

import com.example.administrator.text.HomeActivity;

import org.apache.log4j.Logger;

import java.util.Calendar;
import java.util.TimeZone;

import app.MyApplication;
import data.SharedPreferencesUtils;
import util.BReceiverUtil.AlarmReceiver;
import util.HomeUtil;
import util.LogUtil;
import util.StringUtil;

public class MyService extends Service{
    private Logger mLogger = Logger.getLogger(MyService.class);
    private int mTime,mBranch;
    private int mTiemInt = 0;
    private int second;
    private boolean start = true;
    private String mType;
    private Context mContext;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        LogUtil.eE("Service","................onBind.......");
        return null;

    }

    @Override
    public int onStartCommand(Intent intent,int flags,int startId) {
        mType = intent.getStringExtra("type");
        LogUtil.eE("Service","................onStartCommand......."+mType);
        if(mType !=null && mType.equals("network")){
            updateNetwork();
        }else {
            if(start){
                start = false;
                if(mType !=null && mType.equals("ok")){
                    String monryTime = (String)SharedPreferencesUtils.getParam(this,HomeUtil.mMoneyTime,"");  //上网的时间
                    int time = (int)SharedPreferencesUtils.getParam(this,HomeUtil.mNetworkingTime,4);        //预约的时长
                    setAlarmManager(time,monryTime);
                }else if(mType !=null && mType.equals("on")){

                    //取消断网通知
                    AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
                    Intent inten = new Intent(getApplicationContext(),AlarmReceiver.class);
                    inten.putExtra("networking","networkingNormal");
                    PendingIntent sender = PendingIntent.getBroadcast(
                            MyService.this,0,inten,0);
                    am.cancel(sender);
                }
                HomeUtil.getHemeUtilNew().getHandlerNew().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        start = true;
                    }
                },3000);
            }
        }

        return Service.START_STICKY;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mContext = MyApplication.getApp().getApplicationContext();
        LogUtil.eE("Service","................onCreate.......");
    }


    @Override public void onDestroy() {
        super.onDestroy();
        if(mTiemInt >0 ){
            Intent i = new Intent(this,MyService.class);
            startService(i);
        }
        LogUtil.eE("Service","................onDestroy.......");
    }

    /**
     *设置一个闹钟服务
     */
    private void setAlarmManager(int time,String monryTime){
        if(time>0){
            mTiemInt = (int)StringUtil.getStringUtilNew().compareTime(monryTime,time);
            Calendar cal = Calendar.getInstance();
            if(mTiemInt >=60){
                mTime = cal.get(Calendar.HOUR_OF_DAY)+(mTiemInt/60);
                if(mTime>24){
                    mTime = mTime -24;
                }
                getBranch(cal,mTiemInt%60);
            }else {
                mTime = cal.get(Calendar.HOUR_OF_DAY);
                getBranch(cal,mTiemInt);
            }
            second = cal.get(Calendar.SECOND);
            mLogger.info("通知--broadcast()-->time.."+mTime+"branch.."+mBranch+"..second.."+second+"...type..."+"networkingNormal"+"..mTiemInt.."+mTiemInt);
            Intent inten = new Intent(getApplicationContext(), AlarmReceiver.class);
            inten.putExtra("networking","networkingNormal");
            PendingIntent sender = PendingIntent.getBroadcast(
                    MyService.this,0,inten,0);
            // We want the alarm to go off 10 seconds from now.
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(System.currentTimeMillis());
            // 这里时区需要设置一下，不然可能个别手机会有8个小时的时间差
            calendar.setTimeZone(TimeZone.getTimeZone("GMT+8"));
            calendar.add(Calendar.SECOND, 10);
            //设置在几点提醒 设置的为13点
            calendar.set(Calendar.HOUR_OF_DAY, mTime);
            //设置在几分提醒 设置的为25分
            calendar.set(Calendar.MINUTE, mBranch);
            //下面这两个看字面意思也知道
            calendar.set(Calendar.SECOND, second);
            AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
            if(Build.VERSION.SDK_INT < 19){
                am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), sender);
            }else{
                am.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),sender);
            }
        }else {
            mTiemInt = 0;
        }
    }

    /**
     * 设置分钟
     */
    private void getBranch(Calendar cal,int timeString){
        if(timeString>9){
            mBranch = cal.get(Calendar.MINUTE)+(timeString-7);
        }else if(timeString>2){
            mBranch = cal.get(Calendar.MINUTE)+(timeString-(timeString-2));
        }else {
            mBranch = cal.get(Calendar.MINUTE)+(timeString-timeString);
        }

        LogUtil.eE("getBranch","....timeString....."+timeString+"..mBranch.."+mBranch);
        if(mBranch >= 60){
            mTime++;
            if(mTime>24){
                mTime = mTime -24;
            }
            mBranch = mBranch - 60;
        }
    }

    /**
     * 更新网络
     */
    private void updateNetwork(){
        Intent intent = new Intent(mContext,AlarmReceiver.class);
        intent.putExtra("networking","updateNetwork");
        PendingIntent pi = PendingIntent.getBroadcast(this,0,intent,0);
        Calendar calendar = Calendar.getInstance();
        AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
        if(Build.VERSION.SDK_INT < 19){
            am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis()+10*1000, pi);
        }else{
            am.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis()+10*1000,pi);
        }
    }



    /**
     * 更新通知
     */
    private void updateNotice(String state){
        String tile;
        int length = state.length();
        LogUtil.eE("Service","..length...."+length);
        if(length == 2 || length == 1){
            tile ="已经连接互联网";
        }else {
            tile ="没有连接互联网";
        }
        Intent intent = new Intent(HomeActivity.mAction);
        intent.putExtra("wifi","updateNotice");
        intent.putExtra("name",tile);
        sendBroadcast(intent);
    }
}
